package com.zhongya666.library.ui

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.GradientDrawable
import android.os.CountDownTimer
import android.util.AttributeSet
import android.view.Gravity
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.zhongya666.library.R
import kotlin.properties.Delegates


/**
 * 列举在实际开发中，大多数要修改的地方，公开了以下方法
 * 1.按钮圆角
 * 2.按钮正常背景色------按钮置灰背景色 （支持渐变色）
 * 3.按钮正常显示的文字--按钮置灰显示的文字
 * 4.按钮正常文字的颜色--按钮置灰文字的颜色
 *
 */
@SuppressLint("AppCompatCustomView")
class TimeButton : TextView {

    private lateinit var countDownTimer: CountDownTimer

    /**
     * xml 中设置倒计时 单位（s）
     */
    private var countDownTime = 60

    /**
     * xml 中设置正常字体文本和倒计时的字体文本
     */
    private var normalText: String? = null
    private var runText: String? = null

    /**
     * xml 中设置正常字体颜色和倒计时的字体颜色
     */
    private var normalTextColor = 0
    private var runTextColor = 0

    /**
     * xml 中设置正常字体背景资源和倒计时的字体背景资源
     */
    private var normalBackgroundResource by Delegates.notNull<Int>()
    private var runBackgroundColorResource by Delegates.notNull<Int>()


    /**
     * 为了使用方便，公开了动态设置背景属性,这样就可以不用写shape文件了
     */
    private var normalBackgroundColor = 0
    private var runBackgroundColor = 0

    /**
     * (务必设置这个点击事件，否则按钮不变色)
     * 按钮的点击事件
     */
    private var listener: (() ->Unit) ? = null
    fun setTimeButtonClickListener(listener: () ->Unit ) {
        this.listener = listener
    }
    /**
     * (一般不用)
     * 倒计时完成通知
     */
    private var timeFinishListener: (() ->Unit) ? = null
    fun setTimeButtonFinishListener(timeFinishListener: () ->Unit ) {
        this.timeFinishListener = timeFinishListener
    }

    init {

        gravity = Gravity.CENTER

        setOnClickListener {
            letRun()
            listener?.invoke()
        }
    }

    constructor(context: Context?) : super(context!!) {}
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {

        val a = context.obtainStyledAttributes(attrs, R.styleable.TimeButton)
        normalText = a.getString(R.styleable.TimeButton_textNormal) ?: "获取验证码"
        runText = a.getString(R.styleable.TimeButton_textRun) ?: "重新获取"
        countDownTime = a.getInt(R.styleable.TimeButton_countDownTime, 60)
        normalTextColor = a.getColor(
            R.styleable.TimeButton_textNormalColor, ContextCompat.getColor(context,
                R.color.white
            ))
        runTextColor = a.getColor(
            R.styleable.TimeButton_textRunColor, ContextCompat.getColor(context,
                R.color.white
            ))
        normalBackgroundResource = a.getResourceId(
            R.styleable.TimeButton_normalBackgroundResource,
            R.drawable.bg_card_blue_rad3
        )
        runBackgroundColorResource = a.getResourceId(
            R.styleable.TimeButton_runBackgroundColorResource,
            R.drawable.bg_card_huise_999_rad3
        )

        text = normalText
        setTextColor(normalTextColor)
        setBackgroundResource(normalBackgroundResource)

        countDownTimer = object : CountDownTimer((countDownTime + 1) * 1000.toLong(),1000){
            override fun onTick(millisUntilFinished: Long) {
                text = "$runText${millisUntilFinished/1000}s"
            }

            override fun onFinish() {
                resetTimeButton()
            }
        }

        a.recycle()
    }



    fun letRun() {
        isClickable = false
        setTextColor(runTextColor)
        if (runBackgroundColor == 0){
            setBackgroundResource(runBackgroundColorResource)
        }else{
            backgroundDrawable.setColor(runBackgroundColor)
            background = backgroundDrawable
        }

        countDownTimer.start()
    }

    private fun resetTimeButton(){
        isClickable = true
        text = normalText
        setTextColor(normalTextColor)
        if (runBackgroundColor == 0){ //如果为0  说明没有动态设置过
            setBackgroundResource(normalBackgroundResource)
        }else{
            backgroundDrawable.setColor(normalBackgroundColor)
            background = backgroundDrawable
        }
        timeFinishListener?.invoke()
    }


    /*****************************************Open***********************************************************/

    /**
     * 设置圆角和背景色
     */

    private val backgroundDrawable = GradientDrawable()
    fun setEasyAttr(
        normalBackgroundColor: Int = ContextCompat.getColor(context, R.color.blue),
        runBackgroundColor: Int = ContextCompat.getColor(context, R.color.color_999),
        radius: Float = 5f,
    ){

        this.normalBackgroundColor = normalBackgroundColor
        this.runBackgroundColor = runBackgroundColor
        backgroundDrawable.cornerRadius = radius
        backgroundDrawable.setColor(normalBackgroundColor)
        background = backgroundDrawable
    }

}